# report.py
#
# Exercise 2.4
# pcost.py

import csv
import logging

logging.basicConfig(
    level=logging.INFO,
    format = '%(asctime)s-%(levelname)s  %(message)s',
    handlers = [
        logging.FileHandler('log.txt', 'at', 'utf-8'), 
        logging.StreamHandler()
    ]
)

def read_portfolio(filename):
    '''
    练习代码，读取并转换为元组
    '''
    portfolio = []

    with open(filename, 'rt') as f:
        rows = csv.reader(f)
        header = next(rows)
        try:
            for row in rows:
                name = row[0]
                shares = int(row[1])
                price = float(row[2])
                # t = (name, shares, price) # 定义为元组，然后追加到列表中
                dict = {'name': name, 'shares': shares, 'price': price}

                portfolio.append(dict)
        except ValueError as e:
            logging.error(f'Bad row: {row} | Error: {e}')
    return portfolio

# output = read_portfolio('Playground/Data/portfolio.csv')
# print(f'final results: \n{output}')

def read_prices(filename):
    '''
    练习代码，读取股票价格并转换为字典
    '''
    prices = {}
    with open(filename, 'rt', encoding='utf-8') as f:
        rows = csv.reader(f)
        
        for row in rows:
            try:
                if len(row) != 2:
                    continue
                name = row[0]
                price = float(row[1])
                prices[name] = price # 不存在将新增键与值，存在键将覆盖值
            except ValueError as e:
                logging.error(f'Bad row: {row} | Error: {e}')
    return prices

# output = read_prices('Playground/Data/prices.csv')
# print(f'final results: \n{output}')

def portfolio_profit():
    '''
    figure out the costs when buying all the stocks in the portfilio
    calculate the difference between the cost and the current price

    '''
    portfolio = read_portfolio('Playground/Data/portfolio.csv')
    prices = read_prices('Playground/Data/prices.csv')

    cost = 0.0
    current = 0.0

    for i in portfolio:
        cost += i['shares'] * i['price']
        current += i['shares'] * prices[i['name']]
    return current-cost

result = portfolio_profit()
print(f'\nfinal profit: \n{result}')  